package com.graduate.emos.wx.db.dao;

import com.graduate.emos.wx.db.pojo.MessageRefEntity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

@Repository
public class MessageRefDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    /*新增数据*/
    public String insert(MessageRefEntity messageRef) {
        messageRef = mongoTemplate.save(messageRef);
        return messageRef.get_id();
    }

    /*查询未读消息的数量*/
    public long searchUnreadCount(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("readFlag").is(false).and("receiverId").is(userId));
        return mongoTemplate.count(query, MessageRefEntity.class);
    }

    /*查询最新消息数量*/
    public long searchLastCount(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("lastFlag").is(true).and("receiverId").is(userId));
        Update update = new Update();
        update.set("lastFlag", false);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, "message_ref");
        return updateResult.getModifiedCount();
    }

    /*修改消息状态*/
    public long updateUnreadMessage(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("readFlag", true);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "message_ref");
        return updateResult.getModifiedCount();
    }

    /*根据id删除消息记录*/
    public long deleteMessageRefById(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, "message_ref");
        return deleteResult.getDeletedCount();
    }

    /*根据userId删除用户所有的消息*/
    public long deleteUserMessageRef(int userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("receiverId").is(userId));
        DeleteResult deleteResult = mongoTemplate.remove(query, "message_ref");
        return deleteResult.getDeletedCount();
    }
}